package com.qf.shop.controller;

import com.qf.shop.annotation.ProcessInfo;
import com.qf.shop.model.FilePath;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin(origins = "*")
public class FileUploadController {

    @Value("${imageServerSaveAddress}")
    private String fileLocation;

    @Value("${imageServerLocation}")
    private String imageServer;

    @PostMapping("/upload")
    @ProcessInfo("上传图片进行图片回显")
    public FilePath upload(@RequestParam(value="avatar",required=false) MultipartFile avatar, HttpServletRequest req){
        //获取种类名字
        System.out.println(avatar);
        String alias = req.getParameter("itemAlias");
        String path = fileLocation+alias;
        File f = new File(path);
        if(!f.exists()){
            f.mkdirs(); //创建目录
        }

        //获取文件名字
        String fileName = avatar.getOriginalFilename();
        //获取文件名后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成新的文件名字
        String newFileName = UUID.randomUUID().toString()+suffix;

        String filePath = alias + "/" + newFileName;
        try {
            avatar.transferTo(new File(fileLocation+filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        FilePath filePath1 = new FilePath();
        filePath1.setFilePath(filePath); //要插入到数据库
        filePath1.setImageUrl(imageServer+filePath);// 前端要展示用

        return filePath1;

    }



}
